package com.xiaoniu.forum.common.utils;

import com.xiaoniu.forum.common.constant.RedisKeyConstant;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class CountUtils {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 记录观看数,将其存入redis
     * @param
     */
    public void countByRedis(String topicId){
        HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
        String key = RedisKeyConstant.SCHEDULING_VIEW_COUNT_KEY;
        if (!ops.hasKey(key,topicId)){
            //如果没有此键值对,创建r
            ops.put(key,topicId,"1");
        }else {
            //如果有值 取出+1 并再次存入
            String value = (String) ops.get(key,topicId);
            Integer count = Integer.parseInt(value);
            ops.put(key,topicId,++ count+"");
        }
    }

    /**
     * 根据key 获取hash类型的值,并转为map
     * @param key
     * @return
     */
    public Map<Object, Object> getAllHashByKey(String key){
        HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
        Map<Object, Object> entries = ops.entries(key);
        return entries;
    }

    public void flush(String key){
        redisTemplate.delete(key);
    }


}
